<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        [v-cloak] {
            display: none;
        }

        .el-tree {
            min-width: 100%;
            display: inline-block;
        }

        .tree {
            overflow: auto;
            max-height: 350px;
        }
    </style>
</head>
<body>
<div id="app" v-cloak>
    <el-row :gutter="20">
        <el-col :span="5">
            <el-button
                    type="text"
                    size="mini"
                    @click="() => appendRoot()">
                <i class="el-icon-circle-plus-outline" title="添加根目录"></i>
            </el-button>
            <el-tree
                    :props="fileProps"
                    :load="loadServerDirNode"
                    @node-click="serverTreeClick"
                    lazy>
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
                  type="text"
                  size="mini"
                  @click="() => append(data)">
                      <i class="el-icon-plus" title="添加子目录"></i>
          </el-button>
        </span>
      </span>
            </el-tree>
        </el-col>

        <el-col :span="16">
            <el-button type="primary" @click="fileUpload">文件上传</el-button>
            <el-button type="primary" @click="uploadDialog=true">上传中心</el-button>
            <el-button type="primary" @click="downloadDialog=true">下载中心</el-button>
            <el-table
                    :data="tableData"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="fileName"
                        label="文件名称">
                </el-table-column>
                <el-table-column
                        prop="fileLength"
                        label="文件大小">
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="上传时间">
                </el-table-column>
                <el-table-column
                        label="操作"
                        fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="openDownloadFile(scope.row)">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[10, 15, 20, 25]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-col>
    </el-row>


    <el-dialog title="添加目录" :visible.sync="addDirDialog">
        <el-form :model="dir">
            <el-form-item label="目录名称">
                <el-input v-model="dir.name" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addDirDialog = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddDir">确 定</el-button>
        </div>
    </el-dialog>

    <el-dialog :title="isDownload?'选择目录':'选择文件'" :visible.sync="fileDialog">
        <div class="tree mt10">
            <el-tree
                    :props="fileProps"
                    :load="loadFileDirNode"
                    ref="localFileTree"
                    lazy>
            </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="fileDialog = false">取 消</el-button>
            <el-button type="primary" @click="toUploadDownload">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog title="上传中心" :visible.sync="uploadDialog">
        <el-table
                :data="uploadData"
                stripe
                style="width: 100%">
            <el-table-column
                    prop="fileName"
                    label="文件名称">
            </el-table-column>
            <el-table-column
                    prop="speed"
                    label="上传速度">
            </el-table-column>
            <el-table-column
                    label="上传进度"
                    fixed="right">
                <template slot-scope="scope">
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="scope.row.progress"></el-progress>
                </template>
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态">
            </el-table-column>
            <el-table-column
                    label="操作"
                    fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" size="small" v-if="scope.row.status=='上传中'" @click="stopJob(scope.row)">暂停</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status=='已暂停'" @click="goOn(scope.row)">继续</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status=='已暂停'" @click="cancelUpload(scope.row)">取消上传</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="uploadDialog = false">取 消</el-button>
            <el-button type="primary">确 定</el-button>
        </div>
    </el-dialog>


    <el-dialog title="下载中心" :visible.sync="downloadDialog">
        <el-table
                :data="downloadData"
                stripe
                style="width: 100%">
            <el-table-column
                    prop="fileName"
                    label="文件名称">
            </el-table-column>
            <el-table-column
                    prop="downloadFilePath"
                    label="下载目录">
            </el-table-column>
            <el-table-column
                    prop="speed"
                    label="下载速度">
            </el-table-column>
            <el-table-column
                    label="下载进度"
                    fixed="right">
                <template slot-scope="scope">
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="scope.row.progress"></el-progress>
                </template>
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态">
            </el-table-column>
            <el-table-column
                    label="操作"
                    fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" size="small" v-if="scope.row.status=='下载中'" @click="stopJob(scope.row)">暂停</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status=='已暂停'" @click="goOnDownload(scope.row)">继续</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status=='已暂停'" @click="cancelDownload(scope.row)">取消下载</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="downloadDialog = false">取 消</el-button>
            <el-button type="primary">确 定</el-button>
        </div>
    </el-dialog>

</div>
</body>
<script th:inline="javascript">
    var serverIp = [[${serverIp}]];
    var websocketPort = [[${websocketPort}]];
    var ctx = [[@{
        /}]] ;
</script>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/0.1.0/lodash.min.js"></script>
<script>
    window.onbeforeunload = function(e) {
        $.ajax({
            type:"get",
            url:ctx+"file/abortAll",
            success:function(){
            }
        })
    };
    let treeId=10000;
    var v = new Vue({
        el: '#app',
        data: function () {
            return {
                fileProps: {
                    label: 'name',
                    children: 'children',
                    isLeaf: 'leaf'
                },
                downloadDialog:false,
                uploadDialog: false,
                addDirDialog: false,
                fileDialog: false,
                dir: {
                    name: null
                },
                uploadData: [],
                tableData: [],
                downloadData:[],
                currentDir: null,
                currentServerDir: null,
                page: 1,
                pageSize: 10,
                total: null,
                websocketUser:null,
                currentFile:null,
                isDownload:false
            }
        },
        mounted() {
            this.websocketUser = this.guid();
            var that=this;
            var ws = new WebSocket("ws://" + serverIp + ":" + websocketPort + "/" + this.websocketUser);
            ws.onmessage = function (res) {
                var obj = JSON.parse(res.data);
                var fileObj=null;
                var status="";
                if(obj.type=="1"){
                    var uploadId = obj.data.uploadId;
                    fileObj = _.find(that.uploadData, function (n) {
                        return n._id == uploadId;
                    })
                    if (fileObj.status=="已暂停"){
                        return;
                    }
                    status="上传中"
                    if (obj.finish) {
                        var index=that.uploadData.indexOf(fileObj)
                        fileObj.progress = 100
                        that.$notify({
                            title: '上传完成',
                            message:fileObj.fileName+"上传完成!"
                        });
                        setTimeout(function(){
                            that.uploadData.splice(index,1)
                            if (that.uploadData.length==0){
                                that.uploadDialog=false;
                            }
                            that.page=1;
                            that.listServerFile(that.currentServerDir, that.page, that.pageSize);
                        },1000)
                    }
                }else{
                    var downloadId = obj.data.downloadId;
                    fileObj = _.find(that.downloadData, function (n) {
                        return n._id == downloadId;
                    })
                    if (fileObj.status=="已暂停"){
                        return;
                    }
                    status="下载中"
                    if (obj.finish) {
                        fileObj.progress = 100
                        fileObj.status="完成"
                        that.$notify({
                            title: '下载完成',
                            message:fileObj.fileName+"下载完成!"
                        });
                    }
                }

                if(!obj.finish) {
                    that.updateProgress(obj,fileObj,status);
                }
            }
            ws.onclose = function (ev) {
                console.log("websocket已断开" + ev);
            }
            this.loadUpload();
            this.loadDownload();
        },
        methods: {
            executeSoft(row){
                var url = encodeURI(row.downloadFilePath+"/"+row.fileName);
                location.href=url;
            },
            updateProgress(obj,fileObj,status){
                var progress = (obj.data.transferLength / obj.data.totalLength) * 100;
                fileObj.progress = parseInt(progress.toFixed(0))
                var speed = obj.data.speed;
                fileObj.speed = speed
                fileObj.status = status
            },
            openDownloadFile(row){
                this.currentFile=row;
                this.isDownload=true;
                this.fileDialog = true;
            },
            serverTreeClick(data){
                this.listServerFile(data.path, 1, 10)
            },
            appendRoot(){
                this.addDirDialog = true;
                this.currentDir = {
                    path:""
                }
            },
            cancelUpload(row){
                var that=this;
                var loading = this.openLoading();
                $.ajax({
                    type:"get",
                    url:ctx+"file/cancelUpload/"+row._id,
                    success:function(data){
                        loading.close()
                        if (data.code==0){
                            var number = that.uploadData.indexOf(row);
                            that.uploadData.splice(number,1);
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            cancelDownload(row){
                var that=this;
                var loading = this.openLoading();
                $.ajax({
                    type:"post",
                    url:ctx+"file/cancelDownload",
                    data:{
                        downloadId:row._id,
                        downloadFilePath:row.downloadFilePath,
                        fileName:row.fileName
                    },
                    success:function(data){
                        loading.close()
                        if (data.code==0){
                            var number = that.downloadData.indexOf(row);
                            that.downloadData.splice(number,1);
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            loadUpload(){
                var that=this;
                $.ajax({
                    type:"get",
                    url:ctx+"file/loadUpload",
                    success:function(data){
                        if (data.code==0){
                            that.uploadData=data.value
                        }
                    }
                })
            },
            loadDownload(){
                var that=this;
                $.ajax({
                    type:"get",
                    url:ctx+"file/loadDownload",
                    success:function(data){
                        if (data.code==0){
                            that.downloadData=data.value
                        }
                    }
                })
            },
            goOn(row){
                var loading = this.openLoading();
                var that=this;
                $.ajax({
                    type:"post",
                    url:ctx+"file/goOnUpload",
                    data:{
                        uploadId: row._id,
                        websocketUser: this.websocketUser,
                        directory: row.directory,
                        filePath: row.clientFilePath
                    },
                    success:function(data){
                        loading.close()
                        if (data.code==0){
                            row.status="准备中";
                        }else{
                            that.$message.error(data.msg);
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            goOnDownload(row){
                var loading = this.openLoading();
                var that=this;
                $.ajax({
                    type:"post",
                    url:ctx+"file/download",
                    data:{
                        downloadId: row._id,
                        fileId: row.fileId,
                        downloadFilePath: row.downloadFilePath,
                        fileName: row.fileName,
                        websocketUser: this.websocketUser
                    },
                    success:function(data){
                        loading.close()
                        if (data.code==0){
                            row.status="准备中";
                        }else{
                            that.$message.error(data.msg);
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            stopJob(row){
                var loading = this.openLoading();
                $.ajax({
                    type:"get",
                    url:ctx+"file/abortUploadOrDownload/"+row._id,
                    success:function(){
                        loading.close()
                        row.status="已暂停";
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            fileUpload() {
                if (this.currentServerDir == null) {
                    this.$notify.error({
                        title: '错误',
                        message: '请选择目录'
                    });
                    return
                }
                this.isDownload=false;
                this.fileDialog = true;
            },
            toUploadDownload() {
                var that = this;
                var currentNode = this.$refs.localFileTree.getCurrentNode();
                var id = this.guid();
                if (!this.isDownload){
                    if (!currentNode.leaf) {
                        this.$notify.error({
                            title: '错误',
                            message: '请选择文件进行上传'
                        });
                        return
                    }
                    var loading = this.openLoading();
                    $.ajax({
                        url: ctx + "/file/upload",
                        type: "post",
                        data: {
                            uploadId: id,
                            websocketUser: this.websocketUser,
                            directory: this.currentServerDir,
                            filePath: currentNode.path
                        },
                        success: function (data) {
                            loading.close()
                            if (data.code==0){
                                that.uploadData.push(JSON.parse(JSON.stringify({
                                    _id: id,
                                    fileName: currentNode.name,
                                    speed: "",
                                    clientFilePath: currentNode.path,
                                    progress: 0,
                                    status:"上传中",
                                    directory:that.currentServerDir
                                })))
                                that.uploadDialog = true;
                                that.fileDialog = false;
                            }else{
                                that.$message.error(data.msg);
                            }
                        },
                        error:function(){
                            loading.close();
                        }
                    })
                }else{
                    var loading = this.openLoading();
                    $.ajax({
                        url: ctx + "/file/download",
                        type: "post",
                        data: {
                            downloadId: id,
                            websocketUser: this.websocketUser,
                            fileId: this.currentFile._id,
                            downloadFilePath: currentNode.path,
                            fileName:this.currentFile.fileName,
                        },
                        success: function (data) {
                            loading.close()
                            if (data.code==0){
                                that.downloadData.push(JSON.parse(JSON.stringify({
                                    _id: id,
                                    fileName: that.currentFile.fileName,
                                    speed: "",
                                    downloadFilePath: currentNode.path,
                                    progress: 0,
                                    status:"下载中",
                                    fileId:that.currentFile._id
                                })))
                                that.downloadDialog = true;
                                that.fileDialog = false;
                            }else{
                                that.$message.error(data.msg);
                            }
                        },
                        error:function(){
                            loading.close();
                        }
                    })
                }
            },
            handleSizeChange(val) {
                this.pageSize=val
                this.listServerFile(this.currentServerDir, this.page, this.pageSize);
            },
            handleCurrentChange(val) {
                this.page=val;
                this.listServerFile(this.currentServerDir, this.page, this.pageSize);
            },
            listServerFile(path, page, pageSize) {
                if (typeof path == "undefined") {
                    return;
                }
                var that = this;
                var loading = this.openLoading();
                $.ajax({
                    type: "post",
                    url: ctx + "file/listServerFile",
                    data: {
                        path: path,
                        page: page,
                        pageSize: pageSize,
                        fileName: ""
                    },
                    success: function (data) {
                        loading.close();
                        if (data.code == 0) {
                            that.tableData = data.value.rows
                            that.total = data.value.total
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })

            },
            dealFileDir(node) {
                var resultLabel = "";
                if (node.parent != null && node.parent.id != 0 && node.parent.parent != null) {
                    label = this.dealFileDir(node.parent)
                    resultLabel += label + "/" + node.data.name;
                } else {
                    resultLabel += node.data.name;
                }
                return resultLabel;
            },
            loadServerDirNode(node, resolve) {
                var that = this;
                var resultLabel = null
                if (node.parent == null) {
                    resultLabel = node.label
                } else {
                    resultLabel = this.dealFileDir(node);
                }
                this.currentServerDir = resultLabel
                var loading = this.openLoading();
                $.ajax({
                    type: "get",
                    url: ctx + "file/listServerDir",
                    data: {
                        path: resultLabel
                    },
                    success: function (data) {
                        loading.close()
                        resolve(data);
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            loadFileDirNode(node, resolve) {
                var that=this;
                var resultLabel = null
                if (node.parent == null) {
                    resultLabel = node.label
                } else {
                    resultLabel = this.dealFileDir(node);
                }
                var loading = this.openLoading();
                $.ajax({
                    type: "get",
                    url: ctx + "file/listLocalFile",
                    data: {
                        path: resultLabel
                    },
                    success: function (data) {
                        loading.close();
                        if (that.isDownload){
                            data=_.filter(data,function(n){
                                return !n.leaf
                            })
                        }
                        resolve(data);
                    },
                    error:function(){
                        loading.close();
                    }
                })
            },
            append(data) {
                this.addDirDialog = true;
                this.currentDir = data;
            },
            confirmAddDir() {
                if (this.dir.name == "" || typeof this.dir.name == "undefined" || this.dir.name == null) {
                    this.$notify.error({
                        title: '错误',
                        message: '请输入目录名称'
                    });
                    return
                }
                var loading = this.openLoading();
                var that=this;
                $.ajax({
                    type:"post",
                    url:ctx+"file/makeDir",
                    data:{
                        dirName:this.dir.name,
                        parentPath:this.currentDir.path
                    },
                    success:function(data){
                        loading.close()
                        if (data.code==0){
                            if (that.currentDir.path==""){
                                that.addDirDialog = false;
                                location.reload();
                            }else{
                                const newChild = {id: treeId++, name: that.dir.name, children: [],leaf:false,path:that.currentDir.path+"/"+that.dir.name};
                                if (!that.currentDir.children) {
                                    that.$set(that.currentDir, 'children', []);
                                }
                                that.currentDir.children.push(newChild);
                                that.addDirDialog = false;
                                that.dir.name=null
                            }
                        }
                    },
                    error:function(){
                        loading.close();
                    }
                })

            },
            openLoading(){
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                return loading;
            },
            guid() {
                function S4() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                }

                return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
            }
        }
    })





</script>
</html>